import 'package:ReadDB/model/dao/node_dao.dart';
import 'package:ReadDB/model/dao/widget_dao.dart';
import 'package:ReadDB/model/widget_model.dart';
import 'package:ReadDB/model/node_model.dart';
import 'package:ReadDB/model/enums.dart';
import 'package:ReadDB/model/widget_po.dart';

import 'read_db.dart';
import 'widget_repository.dart';

/// Widget数据仓库
class WidgetDbRepository implements WidgetRepository {
  final DbManager storage;

  WidgetDAO _widgetDAO;
  NodeDAO _nodeDAO;

  WidgetDbRepository(this.storage) {
    _widgetDAO = WidgetDAO(storage);
    _nodeDAO = NodeDAO(storage);
  }

  @override
  Future<List<WidgetModel>> loadWidgets(WidgetFamily family) async {
    var data = await _widgetDAO.queryByFamily(family);
    var widgets = data.map((e) => WidgetPo.fromJson(e)).toList();
    return widgets.map(WidgetModel.fromPo).toList();
  }

  @override
  Future<List<NodeModel>> loadNode(WidgetModel widgetModel) async {
    var data = await _nodeDAO.queryById(widgetModel.id);
    var nodes = data.map((e) => NodeModel.fromJson(e)).toList();
    return nodes;
  }

  @override
  Future<List<WidgetModel>> loadWidget(List<int> id) async {
    var data = await _widgetDAO.queryByIds(id);
    var widgets = data.map((e) => WidgetPo.fromJson(e)).toList();
    if (widgets.length > 0) return widgets.map(WidgetModel.fromPo).toList();
    return null;
  }
}
